package com.lankystar.sos.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

public class FileServiceImpl {

	@SuppressWarnings("resource")
	public static String uploadFile(File file) throws FileNotFoundException, IOException {
		String basePath = "http://sailcloud.gicp.net:10008/lankystarSOS/";
		InputStream in = new FileInputStream(file);
		@SuppressWarnings("deprecation")
		String dir = ServletActionContext.getRequest().getRealPath("upload/");
		File fileLocation = new  File(dir);
		// 此处也可以在应用根目录手动建立目标上传目录
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdir();
			if (!isCreated) {
				// 目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。
				return null;
			}
		}
		// 创建文件唯一名称
		String fileName = new Date().getTime()+"1"+".jpg";
		File uploadFile = new File(dir, fileName);
		String url = basePath + "upload"+"/" + fileName;
		OutputStream out = new FileOutputStream(uploadFile);
		byte[] buffer = new byte[1024 * 1024];
		int length;
		while ((length = in.read(buffer)) > 0) {
			out.write(buffer, 0, length);
		}
		in.close();
		out.close();
	return url;
}
}
